package com.tanhua.app.controllerservice;

import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.VoiceApi;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.domain.vo.VoiceVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ShizhanService {
    @Autowired
    private FastFileStorageClient client; //fastdfs客户端
    @Autowired
    private FdfsWebServer fdfsWebServer; //nigx服务器
    @Reference
    private VoiceApi voiceApi;
    @Reference
    private FriendsApi friendApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private UserLikeApi userLikeApi;

    public ResponseEntity sendVoice(MultipartFile soundFile) throws IOException {
        //存入fastdfs服务器
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), FileUtil.extName(soundFile.getOriginalFilename()), null);
        //获取negix反向代理地址
        String webServerUrl = fdfsWebServer.getWebServerUrl();
        //拼接成新的地址
        String voicePath=webServerUrl+storePath.getFullPath();
        //存入对象中
        Voice voice = new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setUserId(UserHolder.getUser().getId());
        voice.setStart(0);  //0代表状态未读
        voice.setVoiceUrl(voicePath);
        voiceApi.saveVoice(voice);

        System.out.println(voicePath);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity receiveVoice() {
        //当前登录用户Id
        Long userId = UserHolder.getUser().getId();

        //判断redis中是否有剩余次数记录,若没有存一个进去
        if(stringRedisTemplate.hasKey("VOICE_SURPLUS_"+userId)==false){
            stringRedisTemplate.opsForValue().set("VOICE_SURPLUS_"+userId,"5",1, TimeUnit.DAYS);
        }

        //获取当前用户的互相关注
        List<Friend> friendList=friendApi.findAllFriends(userId);

        //获取当前用户的喜欢
        List<UserLike> likeUser=userLikeApi.likeUser(userId);

        //查询状态为0(表示未读的语音)
        List<Voice> voiceList = voiceApi.findVoice(0);

        //遍历循坏排除自己,好友,我喜欢的人
        Iterator<Voice> iterator = voiceList.iterator();
        while (iterator.hasNext()){
            Long id = iterator.next().getUserId();
            //把自己排除出去
            if (id.equals(userId)){
                iterator.remove();
                continue;
            }
            //把好友排除出去
            if (id.equals(friendList.iterator().next().getFriendId())){
                iterator.remove();
                continue;
            }
            //把我喜欢的人排除出去
            if (id.equals(likeUser.iterator().next().getLikeUserId())){
                iterator.remove();
                continue;
            }
        }
        //把排除之后的数据封装到Vo
        VoiceVo voiceVo = new VoiceVo();
        String s = stringRedisTemplate.opsForValue().get("VOICE_SURPLUS_" + userId);
        int voiceSurplus = Integer.parseInt(s);
        for (Voice voice : voiceList) {
            UserInfo userInfo = userInfoApi.findUserInfo(voice.getUserId());
            voiceVo.setAge(userInfo.getAge());
            voiceVo.setAvatar(userInfo.getAvatar());
            voiceVo.setGender(userInfo.getGender());
            voiceVo.setNickname(userInfo.getNickname());
            voiceVo.setId(userInfo.getId().intValue());
            voiceVo.setSoundUrl(voice.getVoiceUrl());
            voiceVo.setRemainingTimes(voiceSurplus);
        }
        //剩余可接收语音次数-1
        if (voiceSurplus>0){
            stringRedisTemplate.boundValueOps("VOICE_SURPLUS_" + userId).increment(-1);
            Integer id = voiceVo.getId();
            String soundUrl = voiceVo.getSoundUrl();
            voiceApi.update(id,soundUrl);
            return ResponseEntity.ok(voiceVo);
        }else {
            //若剩余可接收语音次数小于等于0次,则返回一个空
            UserInfo userInfo=userInfoApi.findById(1);
            VoiceVo voiceVo1 = new VoiceVo();
            voiceVo1.setGender(userInfo.getGender());
            voiceVo1.setRemainingTimes(0);
            voiceVo1.setAge(userInfo.getAge());
            voiceVo1.setAvatar(userInfo.getAvatar());
            voiceVo1.setNickname(userInfo.getNickname());
            voiceVo1.setId(userInfo.getId().intValue());
            voiceVo1.setSoundUrl("");
            return ResponseEntity.ok(voiceVo1);
        }
    }
}
